package com.fingard.dsp.bank.directbank.glb01;

import com.fingard.constant.Format;
import com.fingard.dsp.bank.directbank.bankInterface.ITransaction;
import com.fingard.dsp.bank.reqrespobj.transaction.Req7515TodayTrans;
import com.fingard.dsp.bank.reqrespobj.transaction.Req7516HisTrans;
import com.fingard.dsp.bank.reqrespobj.transaction.RetAtsTrans;
import com.fingard.dsp.bank.reqrespobj.transaction.detail.RetAtsTransDetail;
import com.fingard.text.StringHelper;
import com.fingard.util.DateHelper;
import com.fingard.xml.XElement;
import com.fingard.xml.XmlTextReader;
import com.fingard.xml.XmlTextWriter;

import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;


public class GLB01Transaction extends GLB01Base implements ITransaction {
    @Override
    public RetAtsTrans d_7516_HisTrans(Req7516HisTrans p_req7516) throws Exception {
        //历史明细查询返回ATS的对象
        RetAtsTrans retAts = new RetAtsTrans(p_req7516.reqHeader);
        retAts.writeStart();//写返回ATS的统一头部信息
        String tmpRespCode = "";
        String tmpRespInfo = "";
        /**
         * 1.按照自然月循环查询
         * 2.每个月有分页，再进行分页查询
         */
        try {
            Calendar tmpCalendarFrom = Calendar.getInstance();
            tmpCalendarFrom.setTime(p_req7516.getDateFrom());

            Calendar tmpCalendarTo = Calendar.getInstance();
            tmpCalendarTo.setTime(p_req7516.getDateTo());

            /**
             * 自然月循环
             */
            int tmpIntDateFrom = 0;
            int tmpIntDateTo = 0;
            while (tmpIntDateFrom <= tmpIntDateTo && tmpRespCode.length() == 0) {
                Calendar tmpClndrStepTo = Calendar.getInstance();
                tmpClndrStepTo.setTime(tmpCalendarFrom.getTime());
                //判断是否跨月
                if (DateHelper.compareMonth(tmpCalendarFrom, tmpCalendarTo) == -1) {
                    //跨月则设置为月末
                    tmpClndrStepTo.set(Calendar.DAY_OF_MONTH, tmpClndrStepTo.getActualMaximum(Calendar.DAY_OF_MONTH));
                } else {
                    tmpClndrStepTo.setTime(tmpCalendarTo.getTime());
                }

                /**
                 * 分页循环，发送报文
                 */
                int tmpNowReadStart = 1;//起始页数
                int tmpNowReadNum = 0;//已查询笔数
                Map<String, Integer> tmpTotalNum = new HashMap<String, Integer>();
                while (tmpNowReadNum == 0 || tmpNowReadNum < tmpTotalNum.get("totalCount")) {
                    XmlTextWriter xmlTextWriter = new XmlTextWriter();
                    GLB01Header glb01Header = new GLB01Header();
                    glb01Header.serviceId = "CBE010201";
                    glb01Header.serialNo = p_req7516.reqHeader.transSeqID;
                    glb01Header.reqTime = p_req7516.reqHeader.transTime.replaceAll(" ", "").replaceAll("-", "").replaceAll(":", "");
                    writeCommonHeader(xmlTextWriter, glb01Header);

                    xmlTextWriter.writeStartElement("body");
                    xmlTextWriter.writeElementString("accountNo", p_req7516.actNum);//账户
                    xmlTextWriter.writeElementString("beginDate", Format.Date8Format.format(tmpCalendarFrom.getTime()));//起始时间
                    xmlTextWriter.writeElementString("endDate", Format.Date8Format.format(tmpClndrStepTo.getTime()));//结束时间
                    xmlTextWriter.writeElementString("turnPageNum", tmpNowReadStart + "");//翻页起始数据
                    xmlTextWriter.writeElementString("turnPageShowNum", getBankConfig().getValueAsString("pageSize"));//默认每页显示数据
                    xmlTextWriter.writeEndDocument();

                    String[] tmpRetBkStr = sendToBank(xmlTextWriter.toXmlString());
                    if (tmpRetBkStr[0].length() == 0) {
                        StringBuilder tmpSbMsg = new StringBuilder();
                        XmlTextReader tmpBkReader = loadBankRespXmlReader(tmpRetBkStr[1], tmpSbMsg);
                        if (tmpBkReader != null) {
                            String returnCode = tmpBkReader.getFirstText("/ebank/head/retCode");
                            String returnMsg = tmpBkReader.getFirstText("/ebank/head/retMessage");
                            if (returnCode != null && "000000".equals(returnCode)) {
                                //符合条件的条数，总明细数
                                String totalCount = tmpBkReader.getFirstText("/ebank/body/turnPageTotalNum");
                                if (tmpTotalNum.containsKey("totalCount")) {
                                    if (!tmpTotalNum.get("totalCount").equals(Integer.valueOf(totalCount))) {
                                        tmpRespCode = "-1";
                                        tmpRespInfo = "相同条件前后查出来的总数不一致";
                                        break;
                                    }
                                } else {
                                    if ("0".equals(totalCount)) {
                                        tmpRespCode = "0";
                                        tmpRespInfo = "查询页:" + tmpNowReadStart + ",明细条数为0";
                                        break;
                                    }
                                    tmpTotalNum.put("totalCount", Integer.valueOf(totalCount));//记录总条数
                                }
                                int readCount = 0;
                                while (tmpBkReader.read("/ebank/body/list/row")) {
                                    XElement readXElement = tmpBkReader.readedXElement;
                                    RetAtsTransDetail tmpRetDetail = new RetAtsTransDetail();
                                    tmpRetDetail.actArea = p_req7516.actArea;//银行地区区域码
                                    tmpRetDetail.actNum = p_req7516.actNum;//银行账号
                                    tmpRetDetail.recAccNum = readXElement.getSingleText("acctNo");//对方账号
                                    tmpRetDetail.recAccName = readXElement.getSingleText("accountName");//对方户名
                                    String tmpRecBank = StringHelper.convertToDBC(readXElement.getSingleText("accountOpenNode")).trim();
                                    tmpRetDetail.recAccBank = tmpRecBank;//对方开户银行
                                    //交易日期
                                    String tranDate = readXElement.getSingleText("transferDate");
                                    tmpRetDetail.tranDate = tranDate.substring(0, 4) + "-" + tranDate.substring(4, 6) + "-" + tranDate.substring(6, 8);
                                    tmpRetDetail.tranTime = tranDate.substring(0, 4) + "-" + tranDate.substring(4, 6) + "-" + tranDate.substring(6, 8) + " 00:00:00";
                                    tmpRetDetail.valueDate = tmpRetDetail.tranDate;//起息日期
                                    String payAmount = readXElement.getSingleText("payAmount");//借方发生额
                                    String recAmount = readXElement.getSingleText("recAmount");//贷方发生额
                                    if (!StringHelper.isNullOrEmpty(payAmount) && Math.abs(Double.parseDouble(payAmount)) != 0) {
                                        tmpRetDetail.cdFlag = "1";//1：借（支出）
                                        tmpRetDetail.tranAmt = Math.abs(Double.parseDouble(payAmount)) + "";//交易金额
                                    } else {
                                        tmpRetDetail.cdFlag = "2";//2：贷（收入）
                                        tmpRetDetail.tranAmt = Math.abs(Double.parseDouble(recAmount)) + "";//交易金额
                                    }
                                    tmpRetDetail.accBal = readXElement.getSingleText("balance");//账号余额
                                    tmpRetDetail.billType = readXElement.getSingleText("vouchersType");//票据类型
                                    tmpRetDetail.billNum = readXElement.getSingleText("vouchersNo");//票据号码
//                                    String abstrAndUsage = readXElement.getSingleText("summary");//支付时存对账码和用途(附言)
//                                    tmpRetDetail.abstr = pickupAbstr(abstrAndUsage);

//                                    tmpRetDetail.usage = abstrAndUsage.split("#")[1];
                                    tmpRetDetail.askNumber = readXElement.getSingleTextNotNull("hostFlowNo");//核心流水号
                                    tmpRetDetail.cur = convertCurToATS(readXElement.getSingleText("currencyType"));//币种
                                    nodeAnalysic(readXElement, tmpRetDetail, getCharset());//根据配置将 银行返回字段summary 分割赋值给对账码和用途
                                    retAts.writeRetDetail(tmpRetDetail);
                                    readCount++;
                                }
                                tmpNowReadNum += readCount;//已查询条数
                                if (Integer.parseInt(totalCount) > tmpNowReadNum) {
                                    //总条数大于已查询条数，说明查询了默认条数的明细
                                    if (readCount != Integer.valueOf(getBankConfig().getValueAsString("pageSize"))) {
                                        tmpRespCode = "-1";
                                        tmpRespInfo = "总条数大于已查询条数,统计明细有误";
                                        break;
                                    }
                                }
                                if (Integer.parseInt(totalCount) < tmpNowReadNum) {
                                    //总条数小于已查询条数,说明数据异常
                                    tmpRespCode = "-1";
                                    tmpRespInfo = "总条数小于已查询条数,统计明细有误";
                                    break;
                                }
                                tmpNowReadStart++;//查询起始页加1
                            } else {
                                tmpRespCode = "-1";
                                tmpRespInfo = returnMsg;
                                break;
                            }
                        } else {
                            tmpRespCode = "-1";
                            tmpRespInfo = tmpSbMsg.toString();
                            break;
                        }
                    } else {
                        tmpRespCode = "-1";
                        tmpRespInfo = tmpRetBkStr[1];
                        break;
                    }
                }
                tmpCalendarFrom = tmpClndrStepTo;
                tmpCalendarFrom.add(Calendar.DAY_OF_MONTH, 1);//下个月
                tmpIntDateFrom = Integer.parseInt(Format.Date8Format.format(tmpCalendarFrom.getTime()));
                tmpIntDateTo = Integer.parseInt(Format.Date8Format.format(tmpCalendarTo.getTime()));
            }
        } catch (Exception e) {
            retAts.writeRespCode("-1");
            retAts.writeRespInfo(e.getMessage());
            e.printStackTrace();
            retAts.writeEnd();
            return retAts;
        }


        if ("-1".equals(tmpRespCode)) {
            retAts.writeRespCode(tmpRespCode);
            retAts.writeRespInfo(tmpRespInfo);
        } else if (retAts.getWrittenRdCount() == 0) {
            retAts.writeRespCode("0");
            retAts.writeRespInfo("交易为空!");
        }

        retAts.writeEndWithoutInsertDB();
        return retAts;
    }

    @Override
    public RetAtsTrans d_7515_TodayTrans(Req7515TodayTrans p_req7515) throws Exception {
        Req7516HisTrans p_req7516 = new Req7516HisTrans(p_req7515.reqHeader);
        p_req7516.actArea = p_req7515.actArea;
        p_req7516.actCur = p_req7515.actCur;
        p_req7516.actNum = p_req7515.actNum;
        String date = Format.Date8Format.format(new Date());
        p_req7516.dateFrom = date;
        p_req7516.dateTo = date;
        return d_7516_HisTrans(p_req7516);
    }
}
